package com.bct.jxc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.bct.jxc.common.Constants;
import com.bct.jxc.common.ErrorManager;
import com.bct.jxc.model.User;

/**
 * 用户类Dao(管理员、普通操作员等)
 * 针对(t_user表进行CRUD)
 * @author ASUS
 *
 */
public class UserDao {
	SqlManager manager = null;
	
	public UserDao() {
		super();
		manager = SqlManager.createInstance();
		manager.connectDB();//换取数据库连接
	}

	/**
	 * 查询用户账号密码是否正确
	 * @param user
	 * @return
	 */
	public boolean loginCheck(User user) {
		boolean res = false;
		try {
			//编写sql语句
			String sql = "select * from t_user where login_name = ? and password=?";
			//封装参数
			Object[] params = {user.getLoginName(),user.getPassword()};
			//获取结果集
			ResultSet rs = manager.executeQuery(sql, params, Constants.PSTM_TYPE);
			while(rs.next()) {
				res = true;
			}
			//manager.closeDB();//关闭数据源之后会报错
		} catch (SQLException e) {
			ErrorManager.printError("UserDao loginCheck()", e);
		}
		return res;
	}
	/**
	 * 通过登录名查询操作者信息
	 * @param username
	 * @return
	 */
	public User getUser(String userName) {
		//编写sql语句
		String sql = "select * from t_user where login_name = ?";
		//封装参数
		Object[] params = new Object[]{userName};
		//获取结果集
		ResultSet rs = manager.executeQuery(sql, params, Constants.PSTM_TYPE);
		User user = null;
		try {
			if(rs != null) {
				while(rs.next()) {
					String loginName = rs.getString("login_name");
					String password = rs.getString("password");
					String name = rs.getString("username");
					String power = rs.getString("power");
					user = new User(loginName, password, name, power);
				}
			}
		} catch (SQLException e) {
			ErrorManager.printError("UserDao getUser()", e);
		}
		return user;
	}
}
